<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('新增采购')" />
    <th:block th:include="include :: datetimepicker-css" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-purchase-add" >

            <input name="orderProductIds" id="orderProductIds"  value="" type="hidden">


            <div class="form-group">
                <label class="col-sm-3 control-label">采购订单号：</label>
                <div class="col-sm-8">
                    <input name="purchaseOrderNumber" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">采购状态 ：</label>
                <div class="col-sm-8">
                    <select class="form-control" name="purchaseOrderState" disabled="disabled">
                        <option value="0">未审批</option>
                        <option value="1">已审批</option>
                        <option value="2">已打款</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">采购单位：</label>
                <div class="col-sm-8">
                    <input name="purchasingUnit" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">采购人：</label>
                <div class="col-sm-8">
                    <input name="purchasingPeople" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">采购日期：</label>
                <div class="col-sm-8">
                    <div class="input-group date">
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                        <input type="text" name="purchaseDateStr" class="form-control" id="datetimepicker-demo-2" placeholder="yyyy-MM-dd">
                    </div>
                </div>
            </div>


            <div class="btn-group-sm pull-right"  role="group">
                <a class="btn btn-primary" onclick="submitHandler()">
                    <i class="fa fa-edit"></i> 保存采购单
                </a>
            </div>


            <div class="btn-group-sm" id="toolbar" role="group">
                <a class="btn btn-primary" onclick="addData()">
                    <i class="fa btn-success"></i> 添加出库商品明细
                </a>

                <a class="btn btn-primary" onclick="addquotationData()">
                    <i class="fa btn-success"></i> 从报价单选取
                </a>
            </div>

            <div class="row">
                <div class="col-sm-12 select-table table-striped">
                    <table id="bootstrap-table"></table>
                </div>
            </div>
        </form>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: datetimepicker-js" />
    <th:block th:include="include :: bootstrap-table-editable-js" />
    <script th:inline="javascript">
        var allStash=[];
        $("#datetimepicker-demo-2").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });

        var prefix = ctx + "system/purchase"
        $("#form-purchase-add").validate({
            focusCleanup: true
        });

        function queryAllStash() {

            var config = {
                url: ctx+"scm/inventory/stash/queryAll",
                type: "post",
                dataType: "json",
                async: false,
                data: null,
                success: function(result) {
                    allStash =result.data;
                }
            };
            $.ajax(config);
        }

        function submitHandler(){

            var data = $("#form-purchase-add").serializeArray();

            var productData = getData();
            if(productData.length==0){
                $.modal.alertError("请录入采购商品信息");
                return;
            }

            for (let i = 0; i <productData.length ; i++) {
                var productCount =  $('#productCount'+i).val();
                var c = i+1;
                if(productCount==null||productCount==undefined||productCount==""){
                    $.modal.alertError("第("+c+")行请录入商品采购数量信息");
                    return ;
                }
            }

            var config = {
                url: prefix + "/add",
                type: "post",
                data: data,
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍候...");
                },
                success: function(result) {
                    debugger;
                    if(result.code==0){
                        $.modal.alertSuccess("保存成功");
                        $.modal.closeTab();
                    }else{
                        $.modal.alertError(result.msg);
                    }
                    //console.log(result);
                }
            };
            $.ajax(config);
        }


        function submitHandler2() {

            if ($.validate.form()) {
                var json = classformToJson($('.form-control'));
                json['id']=0;
                if(json['purchaseOrderNumber']==null||json['purchaseOrderNumber']==undefined||json['purchaseOrderNumber']==""){
                    $.modal.alertError("请录入采购订单号");
                    return;
                }
                var productData = getData();
                if(productData.length==0){
                    $.modal.alertError("请录入采购商品信息");
                    return;
                }
                for (let i = 0; i <productData.length ; i++) {
                    var product = productData[i];
                    var stashId = product.stashId;
                    var productCount = product.productCount;
                    if(stashId==null||stashId==undefined||stashId==""){
                        $.modal.alertError("请录入采购商品仓库信息");
                        return ;
                    }
                    if(productCount==null||productCount==undefined||productCount==""||productCount=="请点击输入"){
                        $.modal.alertError("请录入采购商品数量信息");
                        return ;
                    }
                }
                json['details']=productData;
                $.operate.saveJson(prefix + "/add", json);
            }

        }
        function addData(){
            // $.modal.closeTab();

            $.operate.selectProduct("/scm/product/popupListPage",selectProductCallback);

            // $("#" + table.options.id).bootstrapTable('append',newRow);

        }

        function addquotationData(){
            // $.modal.closeTab();

            $.operate.selectProduct("/system/quotation/quotationListPage",selectquotationCallback);

            // $("#" + table.options.id).bootstrapTable('append',newRow);

        }

        function selectquotationCallback(quotationId){
            console.log("selectquotationCallback"+quotationId);

            var config = {
                url: ctx+"system/quotation/detail/"+quotationId,
                type: "post",
                dataType: "json",
                data: null,
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍候...");
                },
                success: function(result) {

                    console.log(result);
                    console.log(result.data);

                    addQuotation(result.data);
                    $.modal.closeLoading();
                }
            }
            $.ajax(config);
        }
        function addQuotation(quotations){
            var count = $("#" + table.options.id).bootstrapTable('getData').length;
            for (let i = 0; i < quotations.length; i++) {
                var quotation = quotations[i];
                var newRow = {
                    index: $.table.serialNumber(count),
                    "purchaseId": '',
                    "supplyQuotationId": quotation.supplyQuotationId,
                    "supplyQuotationCode": '',
                    "scmSupplyQuotationDetailId": quotation.id,
                    "detailType": 'quotation',
                    "productId": quotation.productId,
                    "productCode": quotation.productCode,
                    "productName": quotation.productName,
                    "productUnit": quotation.productUnit,
                    "productSpec": quotation.productSpec,
                    "productCount": quotation.productCount,
                    "price": quotation.price,
                    "remark": quotation.remark,
                    "taxRate": quotation.taxRate,
                    "discountRate": quotation.discountRate,
                    "amt": quotation.amt
                }
                sub.addRow(newRow);
            }

        }

        /* 查询表格所有数据值 */
        function getData(){
            var data = $("#" + table.options.id).bootstrapTable('getData');
            // alert(JSON.stringify(data))
            return data;
        }

        function selectProductCallback(productId) {

            console.log("selectProductCallback"+productId);

            var config = {
                url: ctx+"scm/product/detail/"+productId,
                type: "post",
                dataType: "json",
                data: null,
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍候...");
                },
                success: function(result) {

                    console.log(result);
                    console.log(result.data);

                    addProduct(result.data);
                    $.modal.closeLoading();
                }
            };
            $.ajax(config);

        }

        function onEditableSave (field, row, rowIndex, oldValue, $el) {

            // alert("字段名：" + field + "，当前值：" + row[field]  + "，旧值：" + oldValue);

        }

        $(function(){
            <!-- datetimepicker示例 -->

            $("#datetimepicker-demo-2").datetimepicker({
                format: "yyyy-mm-dd",
                minView: "month",
                autoclose: true
            });

            var id = $("#id").val();
            if(id==null||id==''){
                id=0;
            }

            var orderProductIds = $("#orderProductIds").val();

            //alert(orderProductIds);
            var options = {
                createUrl: prefix + "/add",
                url:   "detail/listByPids?productCodes="+orderProductIds,
                pagination: false,
                showSearch: false,
                showRefresh: false,
                showToggle: false,
                showColumns: false,
                sidePagination: "client",
                columns: [{
                    checkbox: true
                },
                    {
                        field: 'index',
                        align: 'center',
                        title: "序号",
                        formatter: function (value, row, index) {
                            var columnIndex = $.common.sprintf("<input type='hidden' name='index' value='%s'>", $.table.serialNumber(index));
                            var columnId = $.common.sprintf("<input type='hidden' name='products[%s].id' value='%s'>", index, row.id);
                            return columnIndex + $.table.serialNumber(index) + columnId;
                        }
                    },
                    {
                        field : 'productId',
                        align: 'center',
                        title : '商品明细ID',
                        formatter: function (value, row, index) {
                            var columnId = $.common.sprintf("<input type='hidden' name='products[%s].productId' value='%s'>", index, row.productId);
                            return columnId +row.productId;
                        }
                    }
                    ,
                    {
                        field : 'productCode',
                        align: 'center',
                        title : '商品编码',
                        formatter: function (value, row, index) {
                            var columnId = $.common.sprintf("<input type='hidden' name='products[%s].productCode' value='%s'>", index, row.productCode);
                            return columnId +row.productCode;
                        }
                    },
                    {
                        field : 'productName',
                        align: 'center',
                        title : '商品名称',
                        formatter: function (value, row, index) {
                            var columnId = $.common.sprintf("<input type='hidden' name='products[%s].productName' value='%s'>", index, row.productName);
                            return columnId +row.productName;
                        }
                    },

                    {
                        field : 'productUnit',
                        align: 'center',
                        title : '商品单位',
                        formatter: function (value, row, index) {
                            var columnId = $.common.sprintf("<input type='hidden' name='products[%s].productUnit' value='%s'>", index, row.productUnit);
                            return columnId +row.productUnit;
                        }
                    },

                    {
                        field : 'productCount',
                        title : '采购数量',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' id='productCount%s' name='products[%s].productCount' value='%s'>", index,index, value);
                            return html;
                        }
                    },
                    {
                        field : 'price',
                        title : '价格',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' id='price%s' name='products[%s].price' value='%s'>", index,index, value);
                            return html;
                        }
                    },
                    {
                        field : 'taxRate',
                        title : '税率%',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' id='taxRate%s' name='products[%s].taxRate' value='%s'>", index,index, value);
                            return html;
                        }
                    },{
                        field : 'discountRate',
                        title : '折扣',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' id='discountRate%s' name='products[%s].discountRate' value='%s'>", index,index, value);
                            return html;
                        }
                    },{
                        field : 'amt',
                        title : '含税金额',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' id='amt%s' name='products[%s].amt' value='%s'>", index,index, value);
                            return html;
                        }
                    },

                    {
                        field: 'remark',
                        title: '备注',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' id='remark%s' name='products[%s].remark' value='%s'>", index,index, value);
                            return html;
                        }                    },
                    {
                        title: '操作',
                        align: 'center',
                        formatter: function(value, row, index) {
                            var actions = [];
                            actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="removeData(\'' + index + '\')"><i class="fa fa-remove"></i>删除</a>');
                            return actions.join('');
                        }
                    }]
            };
            $.table.init(options);
        });



        function removeData(index){

            var data = $("#" + table.options.id).bootstrapTable('getData');
            data.splice(index, 1);

            $("#" + table.options.id).bootstrapTable('load', data);

        }


        function addProduct(productData) {
            var count = $("#" + table.options.id).bootstrapTable('getData').length;

           /* var newRow = {
                index: $.table.serialNumber(count),
                productId: productData.id,
                productCode: productData.productCode,
                productName: productData.productName,
                productUnit: productData.productUnit,
                productCount: '',
                remark: '',
            };*/

            var newRow = {
                index: $.table.serialNumber(count),
                "purchaseId": '',
                "supplyQuotationId": '',
                "supplyQuotationCode": '',
                "scmSupplyQuotationDetailId": '',
                "detailType": "",
                "productId": productData.id,
                "productCode": productData.productCode,
                "productName": productData.productName,
                "productUnit": productData.productUnit,
                "productSpec": "",
                "productCount": '',
                "price": "",
                "remark": "",
                "taxRate": "",
                "discountRate": "",
                "amt": ""
            }

            sub.addRow(newRow);

        }

        function classformToJson(form) {
            var jsonObj = {};
            form.each(function (){
                let val = $(this).val();
                let name = $(this).attr('name');
                jsonObj[name] = val;
            })
            return jsonObj;
        }
    </script>
</body>
</html>
